﻿using Dapper;
using Infrastructure.DataBaseConnect;
using Infrastructure.IRepository;
using Model;
using Model.BusinessModel;
using Model.BusinessModel.OutPut;
using Model.DomainModel;

namespace Infrastructure.Repository
{
    /// <summary>
    /// 流程申请仓储接口实现
    /// </summary>
    public class FlowApplyRepository : Repository<FlowApply>, IFlowApplyRepository
    {

        /// <summary>
        /// 根据申请名称获取申请数据
        /// </summary>
        /// <param name="applyTitle">申请名称</param>
        /// <returns></returns>
        public FlowApply? GetFlowApplyByApplyTitle(string applyTitle)
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = " select  * from FlowApply where ApplyTitle  = @ApplyTitle ";
            return connection.QueryFirstOrDefault<FlowApply>(sql, new { ApplyTitle = applyTitle });

        }

        /// <summary>
        /// 根据申请id获取数据
        /// </summary>
        /// <param name="flowApplyId">申请id</param>
        /// <returns></returns>
        public FlowApplyExtendOutPut? GetFlowApplyByApplyId(string flowApplyId)
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = @" select ep.ApplyTitle,ep.FlowId,ep.IsPublish,er.FormJson,ep.FormData,ep.FlowContent,ep.UrgentIndex,ep.Remark,ep.CurrentNodeId,ep.FlowApplyState from  FlowApply as ep 
                            inner join Flow as ef on ep.FlowId = ef.FlowId
                            inner join Form as er on ep.FormId = er.FormId
                            where ep.FlowApplyId = @FlowApplyId ";
            return connection.QueryFirstOrDefault<FlowApplyExtendOutPut>(sql, new { FlowApplyId = flowApplyId });

        }

        /// <summary>
        /// 更新流程状态
        /// </summary>
        /// <param name="flowApplyId">流程id</param>
        /// <param name="flowApplyState">流程状态</param>
        /// <returns></returns>
        public bool UpdateFlowApplyState(string flowApplyId, int flowApplyState)
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = @" update FlowApply set FlowApplyState=@FlowApplyState where FlowApplyId = @FlowApplyId";
            var count = connection.Execute(sql, new { FlowApplyId = flowApplyId, FlowApplyState= flowApplyState });
            if (count > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 根据流程id,获取申请流程
        /// </summary>
        /// <param name="flowId">流程id</param>
        /// <returns></returns>
        public List<FlowApply> GetFlowApplyByFlowId(string flowId)
        {
            string sql = " select * from FlowApply where FlowId=@FlowId ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<FlowApply>(sql, new { FlowId = flowId }).ToList();
        }
    }
}
